package com.caigou.modules.famous.ui.famous.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.Logger
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.famous.R
import com.caigou.modules.famous.adpter.FamousItemAdapter
import com.caigou.modules.famous.bean.FamousBean
import com.caigou.modules.famous.databinding.FragmentFamousShaBangBinding
import com.caigou.modules.famous.ui.famous.FamousActivity
import com.caigou.modules.famous.viewmodel.FamousViewModel
import com.caigou.modules.famous.widget.FamousFilterDialog
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/08
 */
@AndroidEntryPoint
class FamousShaBangFragment : BaseFragment() {
    private var _binding: FragmentFamousShaBangBinding? = null
    private val binding get() = _binding!!

    private val famousViewModel: FamousViewModel by viewModels()

    private var sort = 1
    private var dareTypeId = 34
    private var clickPos = -1

    private val mAdapter: FamousItemAdapter by lazy {
        FamousItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentFamousShaBangBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.shaBangSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchFamousList()
            }
        }

        binding.shaBangRecyclerView.run {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val userId = mAdapter.getItem(position).userId
            val famousType = (requireActivity() as FamousActivity).famousType
            ARouter.getInstance().build(RouterPath.Famous.PAGE_PERSONAL)
                .withInt(AppConstants.FAMOUS_TYPE, famousType)
                .withString(AppConstants.USER_ID, userId)
                .navigation()
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            clickPos = position
            when (view.id) {
                R.id.item_famous_ll_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        val item = mAdapter.data[position]
                        if (item.like) {
                            return@setOnItemChildClickListener
                        }
                        val famousType = (requireActivity() as FamousActivity).famousType
                        famousViewModel.setLike(item.dareContentId, famousType, AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_famous_ll_subscribe -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        val item = mAdapter.data[position]
                        val famousType = (requireActivity() as FamousActivity).famousType
                        famousViewModel.setSubscribe(dareTypeId, famousType, AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.shaBangRgSelector.setOnCheckedChangeListener { group, checkedId ->
            dareTypeId = when (checkedId) {
                binding.shaBangBtnShaYiXiao.id -> 34
                binding.shaBangBtnSha5ma.id -> 35
                binding.shaBangBtnShaYiTou.id -> 36
                binding.shaBangBtnShaYiWei.id -> 37
                binding.shaBangBtnShaYiDuan.id -> 38
                binding.shaBangBtnShaYiHang.id -> 39
                binding.shaBangBtnShaErWei.id -> 40
                binding.shaBangBtnShaErXiao.id -> 41
                binding.shaBangBtnShaBanBo.id -> 42
                else -> 34
            }
            fetchFamousList()
        }

        binding.shaBangTvFilter.setOnClickListener {
            Logger.d(sort)
            val dialog = FamousFilterDialog(requireActivity(), sort)
            dialog.apply {
                rgFamousFilter.setOnCheckedChangeListener { group, checkedId ->
                    sort = when (checkedId) {
                        btnTotal.id -> 1
                        btnRate.id -> 2
                        btnNewest.id -> 3
                        else -> 1
                    }
                    fetchFamousList()
                    dismiss()
                }
                show()
            }
        }

        LiveDataBus.get().with(BusKey.FAMOUS_TYPE_CHANGE, Int::class.java).observe(this) {
            fetchFamousList()
        }
    }

    override fun lazyLoad() {
        fetchFamousList()
    }

    override fun onBack() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(famousViewModel.shaBangListLiveData, ::handleGetShaBangFamousList)
        observe(famousViewModel.likeLiveData, ::handleSetLike)
        observe(famousViewModel.subscribeLiveData, ::handleSetSubscribe)
    }

    private fun handleGetShaBangFamousList(result: Resource<FamousBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.shaBangSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取杀榜列表异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.shaBangSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                mAdapter.setList(result.data!!.list)
            }
        }
    }

    private fun handleSetLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                val item = mAdapter.data[clickPos]
                item.like = true
                item.nicePoint += 1
                mAdapter.notifyItemChanged(clickPos)
            }
        }
    }

    private fun handleSetSubscribe(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("订阅失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                val item = mAdapter.data[clickPos]
                item.subscribe = !item.subscribe
                mAdapter.notifyItemChanged(clickPos)
            }
        }
    }

    private fun fetchFamousList() {
        val currentUserId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        val famousType = (requireActivity() as FamousActivity).famousType
        famousViewModel.getShaBangFamousList(dareTypeId, famousType, sort, currentUserId)
    }
}